from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from app.config import Config
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

db = SQLAlchemy()
login_manager = LoginManager()

def create_app(config_class=Config):
    app = Flask(__name__,
                template_folder='templates',  # 指定模板目录
                static_folder='static')       # 指定静态文件目录
    
    app.config.from_object(config_class)

    try:
        db.init_app(app)
        login_manager.init_app(app)
        login_manager.login_view = 'auth.login'

        # 注册蓝图
        from app.routes import (
            main_bp, auth_bp, admin_bp,
            data_bp, cleaning_bp, analysis_bp
        )
        
        app.register_blueprint(main_bp)
        app.register_blueprint(auth_bp)
        app.register_blueprint(admin_bp)
        app.register_blueprint(data_bp)
        app.register_blueprint(cleaning_bp)
        app.register_blueprint(analysis_bp)

        # 导入模型
        from app.models import User

        # 创建所有数据库表
        with app.app_context():
            db.create_all()

    except Exception as e:
        logger.error(f"Error initializing app: {e}")
        raise

    return app 